﻿using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Net;
using System.Text;

namespace ScrumFactory.Services.Clients.AuthProviders {

    [Export(typeof(IAuthorizationProviderService))]
    public class GoogleAuthorizationProviderClient : IAuthorizationProviderService {

        [Import]
        private IClientHelper ClientHelper { get; set; }

        #region IAuthorizationProviderService Members

        public string ProviderName {
            get {
                return "Google";
            }
        }


        public string ProviderImageUrl {
            get {
                return @"\Images\AuthorizationProviders\GoogleLogo.png";
            }
        }


        public string GetAuthorizationToken(string user, string password) {
 
            String token = null;

            // creates the post data
            ASCIIEncoding encoding = new ASCIIEncoding();
            string postData = "accountType={0}&Email={1}&Passwd={2}&service=cp&source=scrumfactory";
            postData = string.Format(postData, "HOSTED_OR_GOOGLE", user, password);
            byte[] data = encoding.GetBytes(postData);

            // creates the request
            HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create("https://www.google.com/accounts/ClientLogin");
            authRequest.Method = "POST";
            authRequest.ContentType = "application/x-www-form-urlencoded";
            authRequest.ContentLength = data.Length;


            // set proxy settings
            authRequest.Proxy = ClientHelper.GetProxy();

            try {

                // Send the data
                Stream newStream = authRequest.GetRequestStream();
                newStream.Write(data, 0, data.Length);
                newStream.Close();

                // makes the request            
                HttpWebResponse response = (HttpWebResponse)authRequest.GetResponse();

                // gets the response
                StreamReader responseReader = new StreamReader(response.GetResponseStream());
                token = responseReader.ReadToEnd();

                if (token.IndexOf("Auth=") < 0)
                    return null;

                token = token.Substring(token.IndexOf("Auth="));
                token = token.Replace("Auth=", "");
            }
            catch (WebException exW) {
                // if login not allowed return null Token
                HttpWebResponse r = exW.Response as HttpWebResponse;                
                if (r!=null && r.StatusCode == HttpStatusCode.Forbidden)
                    return null;
                // otherwise, throws the exepetion
                throw new ScrumFactory.Exceptions.ScrumFactoryException(exW.Message);
            }
            catch (Exception ex) {
                throw new ScrumFactory.Exceptions.ScrumFactoryException(ex.Message);
            }


            return token;

        }

        public bool ValidadeToken(string token, string user) {
            throw new NotImplementedException();
        }


        public bool PasswordRequired {
            get {
                return true;
            }
        }

        public bool IsNetworkUser {
            get {
                return false;
            }
        }

        #endregion
    }
}
